package com.wlz.framework.protocol.http;

import com.wlz.framework.Invocation;
import com.wlz.framework.register.LocalRegister;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;

/**
 * @author wlz
 * @date 2022-07-11  9:00 下午
 */
@Slf4j
public class HttpServerHandler {

    public void handler(HttpServletRequest request, HttpServletResponse response) {
        log.info(" HttpServerHandler handler .... ");

        try {
            ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
            Invocation  invocation = (Invocation) ois.readObject();


            String interfaceName = invocation.getInterfaceName();
            Class implClass = LocalRegister.get(interfaceName);

            Method method = implClass.getMethod(invocation.getMethodName(), invocation.getParamTypes());

            String result = (String)method.invoke(implClass.newInstance(), invocation.getParams());
            log.info("tomcat:  {}", result);
            IOUtils.write(result, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
